package JZ56_删除链表中重复的结点;


import java.util.HashSet;
import java.util.Set;

class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}

public class Solution {
    public ListNode deleteDuplication(ListNode pHead) {
         if (pHead == null){
             return null;
         }
         Set<Integer> set = new HashSet<>();
         ListNode pre = pHead;
         ListNode cur = pHead.next;
         while(cur != null){
            if(cur.val == pre.val){
                set.add(cur.val);
            }
            pre = cur;
            cur = cur.next;
         }
         while (pHead != null && set.contains(pHead.val)){
             pHead = pHead.next;
         }
         if (pHead == null){
             return null;
         }

         pre = pHead;
         cur = pHead.next;
         while (cur != null){
             if (set.contains(cur.val)){
                 pre.next = cur.next;
                 cur = cur.next;
             }else {
                 pre = cur;
                 cur = cur.next;
             }
         }

         return pHead;
    }
}